/**
 * 严肃声明：
 * 开源版本请务必保留此注释头信息，若删除我方将保留所有法律责任追究！
 * 本系统已申请软件著作权，受国家版权局知识产权以及国家计算机软件著作权保护！
 * 可正常分享和学习源码，不得用于违法犯罪活动，违者必究！
 * Copyright (c) 2019-2021 十三 all rights reserved.
 * 版权所有，侵权必究！
 */
package ltd.newbee.mall.api.admin;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import ltd.newbee.mall.api.admin.param.BatchIdParam;
import ltd.newbee.mall.api.admin.param.GoodsAddParam;
import ltd.newbee.mall.api.admin.param.GoodsEditParam;
import ltd.newbee.mall.common.Constants;
import ltd.newbee.mall.common.ServiceResultEnum;
import ltd.newbee.mall.config.annotation.TokenToAdminUser;
import ltd.newbee.mall.entity.*;
import ltd.newbee.mall.service.DeliveryFeeService;
import ltd.newbee.mall.service.GoodsSpecService;
import ltd.newbee.mall.service.NewBeeMallCategoryService;
import ltd.newbee.mall.service.NewBeeMallGoodsService;
import ltd.newbee.mall.util.BeanUtil;
import ltd.newbee.mall.util.PageQueryUtil;
import ltd.newbee.mall.util.Result;
import ltd.newbee.mall.util.ResultGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 13
 * @qq交流群 796794009
 * @email 2449207463@qq.com
 * @link https://github.com/newbee-ltd
 */
@RestController
@Api(value = "v1", tags = "8-3.后台管理系统商品模块接口")
@RequestMapping("/manage-api/v1")
public class NewBeeAdminGoodsInfoAPI {

    private static final Logger logger = LoggerFactory.getLogger(NewBeeAdminGoodsInfoAPI.class);

    @Resource
    private NewBeeMallGoodsService newBeeMallGoodsService;
    @Resource
    private NewBeeMallCategoryService newBeeMallCategoryService;

    @Autowired
    private GoodsSpecService goodsSpecService;

    /**
     * 列表
     */
    @RequestMapping(value = "/goods/list", method = RequestMethod.GET)
    @ApiOperation(value = "商品列表", notes = "可根据名称和上架状态筛选")
    public Result list(@RequestParam(required = false) @ApiParam(value = "页码") Integer pageNumber,
                       @RequestParam(required = false) @ApiParam(value = "每页条数") Integer pageSize,
                       @RequestParam(required = false) @ApiParam(value = "商品名称") String goodsName,
                       @RequestParam(required = false) @ApiParam(value = "上架状态 0-上架 1-下架") Integer goodsSellStatus, @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        if (pageNumber == null || pageNumber < 1 || pageSize == null || pageSize < 10) {
            return ResultGenerator.genFailResult("分页参数异常！");
        }
        Map params = new HashMap(8);
        params.put("page", pageNumber);
        params.put("limit", pageSize);
        if (StringUtils.hasText(goodsName)) {
            params.put("goodsName", goodsName);
        }
        if (goodsSellStatus != null) {
            params.put("goodsSellStatus", goodsSellStatus);
        }
        PageQueryUtil pageUtil = new PageQueryUtil(params);
        return ResultGenerator.genSuccessResult(newBeeMallGoodsService.getNewBeeMallGoodsPage(pageUtil));
    }

    /**
     * 添加
     */
    @RequestMapping(value = "/goods", method = RequestMethod.POST)
    @ApiOperation(value = "新增商品信息", notes = "新增商品信息")
    public Result save(@RequestBody @Valid GoodsAddParam goodsAddParam, @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        NewBeeMallGoods newBeeMallGoods = new NewBeeMallGoods();
        BeanUtil.copyProperties(goodsAddParam, newBeeMallGoods);

        // 调用修改后的service方法，传入规格属性
        String result = newBeeMallGoodsService.saveNewBeeMallGoods(newBeeMallGoods, goodsAddParam.getSpecAttrs());
        if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(result);
        }
    }


    /**
     * 修改
     */
    @RequestMapping(value = "/goods", method = RequestMethod.PUT)
    @ApiOperation(value = "修改商品信息", notes = "修改商品信息")
    public Result update(@RequestBody @Valid GoodsEditParam goodsEditParam, @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        NewBeeMallGoods newBeeMallGoods = new NewBeeMallGoods();
        BeanUtil.copyProperties(goodsEditParam, newBeeMallGoods);

        // 调用修改后的service方法，传入规格属性
        String result = newBeeMallGoodsService.updateNewBeeMallGoods(newBeeMallGoods, goodsEditParam.getSpecAttrs());
        if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(result);
        }
    }

    /**
     * 详情
     */
    @GetMapping("/goods/{id}")
    @ApiOperation(value = "获取单条商品信息", notes = "根据id查询")
    public Result info(@PathVariable("id") Long id, @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        Map goodsInfo = new HashMap(8);
        NewBeeMallGoods goods = newBeeMallGoodsService.getNewBeeMallGoodsById(id);
        if (goods == null) {
            return ResultGenerator.genFailResult(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }
        goodsInfo.put("goods", goods);
        GoodsCategory thirdCategory;
        GoodsCategory secondCategory;
        GoodsCategory firstCategory;
        thirdCategory = newBeeMallCategoryService.getGoodsCategoryById(goods.getGoodsCategoryId());
        if (thirdCategory != null) {
            goodsInfo.put("thirdCategory", thirdCategory);
            secondCategory = newBeeMallCategoryService.getGoodsCategoryById(thirdCategory.getParentId());
            if (secondCategory != null) {
                goodsInfo.put("secondCategory", secondCategory);
                firstCategory = newBeeMallCategoryService.getGoodsCategoryById(secondCategory.getParentId());
                if (firstCategory != null) {
                    goodsInfo.put("firstCategory", firstCategory);
                }
            }
        }
        return ResultGenerator.genSuccessResult(goodsInfo);
    }

    /**
     * 批量修改销售状态
     */
    @RequestMapping(value = "/goods/status/{sellStatus}", method = RequestMethod.PUT)
    @ApiOperation(value = "批量修改销售状态", notes = "批量修改销售状态")
    public Result delete(@RequestBody BatchIdParam batchIdParam, @PathVariable("sellStatus") int sellStatus, @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        if (batchIdParam == null || batchIdParam.getIds().length < 1) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        if (sellStatus != Constants.SELL_STATUS_UP && sellStatus != Constants.SELL_STATUS_DOWN) {
            return ResultGenerator.genFailResult("状态异常！");
        }
        if (newBeeMallGoodsService.batchUpdateSellStatus(batchIdParam.getIds(), sellStatus)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("修改失败");
        }
    }


    /**
     * 根据商品ID获取规格属性列表
     */
    @GetMapping("/spec/attrs/{goodsId}")
    public Result getAttrsByGoodsId(@PathVariable Long goodsId) {
        try {
            List<GoodsSpecAttr> attrs = goodsSpecService.getAttrsByGoodsId(goodsId);

            return ResultGenerator.genSuccessResult(attrs);
        } catch (Exception e) {
            return ResultGenerator.genFailResult("获取规格属性失败: " + e.getMessage());
        }
    }

    /**
     * 根据属性ID获取属性值列表
     */
    @GetMapping("/spec/values/{attrId}")
    public Result getValuesByAttrId(@PathVariable Long attrId) {
        try {
            List<GoodsSpecValue> values = goodsSpecService.getValuesByAttrId(attrId);
            return ResultGenerator.genSuccessResult(values);
        } catch (Exception e) {
            return ResultGenerator.genFailResult("获取属性值失败: " + e.getMessage());
        }
    }

    /**
     * 根据商品ID获取所有属性值
     */
    @GetMapping("/spec/values/goods/{goodsId}")
    public Result getValuesByGoodsId(@PathVariable Long goodsId) {
        try {
            List<GoodsSpecValue> values = goodsSpecService.getValuesByGoodsId(goodsId);
            return ResultGenerator.genSuccessResult(values);
        } catch (Exception e) {
            return ResultGenerator.genFailResult("获取属性值失败: " + e.getMessage());
        }
    }

    /**
     * 添加规格属性
     */
    @PostMapping("/spec/attr")
    public Result addAttr(@RequestBody GoodsSpecAttr attr) {
        try {
            boolean success = goodsSpecService.saveAttr(attr);
            if (success) {
                return ResultGenerator.genSuccessResult("添加成功");
            } else {
                return ResultGenerator.genFailResult("添加失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("添加规格属性失败: " + e.getMessage());
        }
    }

    /**
     * 更新规格属性
     */
    @PutMapping("/spec/attr")
    public Result updateAttr(@RequestBody GoodsSpecAttr attr) {
        try {
            boolean success = goodsSpecService.saveAttr(attr);
            if (success) {
                return ResultGenerator.genSuccessResult("更新成功");
            } else {
                return ResultGenerator.genFailResult("更新失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("更新规格属性失败: " + e.getMessage());
        }
    }

    /**
     * 删除规格属性
     */
    @DeleteMapping("/spec/attr/{id}")
    public Result deleteAttr(@PathVariable Integer id) {
        try {
            boolean success = goodsSpecService.deleteAttr(id);
            if (success) {
                return ResultGenerator.genSuccessResult("删除成功");
            } else {
                return ResultGenerator.genFailResult("删除失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("删除规格属性失败: " + e.getMessage());
        }
    }

    /**
     * 添加属性值
     */
    @PostMapping("/spec/value")
    public Result addValue(@RequestBody GoodsSpecValue value) {
        try {
            boolean success = goodsSpecService.saveValue(value);
            if (success) {
                return ResultGenerator.genSuccessResult("添加成功");
            } else {
                return ResultGenerator.genFailResult("添加失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("添加属性值失败: " + e.getMessage());
        }
    }

    /**
     * 更新属性值
     */
    @PutMapping("/spec/value")
    public Result updateValue(@RequestBody GoodsSpecValue value) {
        try {
            boolean success = goodsSpecService.saveValue(value);
            if (success) {
                return ResultGenerator.genSuccessResult("更新成功");
            } else {
                return ResultGenerator.genFailResult("更新失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("更新属性值失败: " + e.getMessage());
        }
    }

    /**
     * 删除属性值
     */
    @DeleteMapping("/spec/value/{id}")
    public Result deleteValue(@PathVariable Integer id) {
        try {
            boolean success = goodsSpecService.deleteValue(id);
            if (success) {
                return ResultGenerator.genSuccessResult("删除成功");
            } else {
                return ResultGenerator.genFailResult("删除失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("删除属性值失败: " + e.getMessage());
        }
    }

    /**
     * 批量保存规格属性
     */
    @PostMapping("/spec/attrs/batch")
    public Result batchSaveAttrs(@RequestBody List<GoodsSpecAttr> attrs) {
        try {
            boolean success = goodsSpecService.batchSaveAttrs(attrs);
            if (success) {
                return ResultGenerator.genSuccessResult("批量保存成功");
            } else {
                return ResultGenerator.genFailResult("批量保存失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("批量保存规格属性失败: " + e.getMessage());
        }
    }

    /**
     * 批量保存属性值
     */
    @PostMapping("/spec/values/batch")
    public Result batchSaveValues(@RequestBody List<GoodsSpecValue> values) {
        try {
            boolean success = goodsSpecService.batchSaveValues(values);
            if (success) {
                return ResultGenerator.genSuccessResult("批量保存成功");
            } else {
                return ResultGenerator.genFailResult("批量保存失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("批量保存属性值失败: " + e.getMessage());
        }
    }



    @Autowired
    private DeliveryFeeService deliveryFeeService;

    @GetMapping("/goods/delivery-fee")
    @ApiOperation(value = "获取快递费配置", notes = "获取当前快递费配置")
    public Result getDeliveryFeeConfig() {
        try {
            DeliveryFeeConfig config = deliveryFeeService.getDeliveryFeeConfig();
            return ResultGenerator.genSuccessResult(config);
        } catch (Exception e) {
            return ResultGenerator.genFailResult("获取快递费配置失败：" + e.getMessage());
        }
    }

    @PostMapping("/goods/delivery-fee")
    @ApiOperation(value = "保存快递费配置", notes = "保存快递费配置")
    public Result saveDeliveryFeeConfig(@RequestBody DeliveryFeeConfig config) {
        try {
            // 验证参数
            if (config == null) {
                return ResultGenerator.genFailResult("参数不能为空");
            }
            if (config.getDefaultFee() == null || config.getDefaultFee().compareTo(BigDecimal.ZERO) < 0) {
                return ResultGenerator.genFailResult("快递费不能为负数");
            }

            // 设置默认启用状态
            config.setEnabled((byte) 1);

            boolean success = deliveryFeeService.updateDeliveryFeeConfig(config);
            if (success) {
                return ResultGenerator.genSuccessResult("保存成功");
            } else {
                return ResultGenerator.genFailResult("保存失败");
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult("保存快递费配置失败：" + e.getMessage());
        }
    }

    @GetMapping("/goods/current-delivery-fee")
    @ApiOperation(value = "获取当前快递费", notes = "获取当前生效的快递费")
    public Result getCurrentDeliveryFee() {
        try {
            BigDecimal deliveryFee = deliveryFeeService.getDefaultDeliveryFee();
            return ResultGenerator.genSuccessResult(deliveryFee);
        } catch (Exception e) {
            return ResultGenerator.genFailResult("获取快递费失败：" + e.getMessage());
        }
    }


}
